package reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created with IntelliJ IDEA
 * Description:反射操作方法学习
 * User:22954
 * Date:2024-04-17
 * Time:14:57
 */
public class ReflecAccessMethod {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> cls = Class.forName("reflection.User");
        Object o = cls.getDeclaredConstructor().newInstance();

        Method hi = cls.getDeclaredMethod("hi");
        hi.invoke(o);//hi
        hi = cls.getDeclaredMethod("hi",null);//null为无参方法
        hi.invoke(o);//hi
        hi = cls.getDeclaredMethod("hi",String.class);
        hi.invoke(o,"Mav");//hi Mav

        Method sentence = cls.getDeclaredMethod("sentence", int.class, String.class, char.class);
        sentence.setAccessible(true);
        Object invoke = sentence.invoke(o, 10, "Kay", 'A');//invoke-调用  默认返回Object  多态向上转型
        System.out.println(invoke);//10 Kay A
        invoke = sentence.invoke(null,2000,"Damon",'D');//static无关对象,可用null默认
        System.out.println(invoke);//2000 Damon D
    }
}
